package com.jacarrichan.demo.dipper.handler;

import com.pactera.dipper.core.Message;
import com.pactera.dipper.presys.cp.http.handler.AbstractHttpClientCommHandler;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpJsonClientHandler extends AbstractHttpClientCommHandler {
    private static final Logger LOG = LoggerFactory.getLogger(HttpJsonClientHandler.class);


    @Override
    protected void receiveHandle(HttpEntity resEntity, Message m) throws Exception {
        byte[] bytes = EntityUtils.toByteArray(resEntity);
        LOG.info("client[{}] receive:[{}]", m.getChannel(), new String(bytes, m.getCharset()));
        m.getTarget().setBody(bytes);
    }


    protected void receiveHandleNoOk(HttpEntity resEntity, Message m, StatusLine statusLine)
            throws Exception {
        byte[] bytes = EntityUtils.toByteArray(resEntity);
        LOG.error("client[{}] [{}] receive:[{}]", m.getChannel(), statusLine,
            new String(bytes, m.getCharset()));

    }


    @Override
    protected byte[] setEntity(HttpPost httppost, Message m) throws Exception {
        byte[] bytes = (byte[]) m.getTarget().getBodys();
        ByteArrayEntity reqentity = new ByteArrayEntity(bytes);
        reqentity.setChunked(true);
        httppost.setEntity(reqentity);
        return bytes;
    }


    @Override
    protected void setHeader(HttpPost httppost, Message m) throws Exception {
        httppost.setHeader("Content-Type", "text/json;charset=".concat(m.getCharset()));
    }

}
